package com.chixing.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.chixing.util.AlipayConfig;
import com.chixing.util.RandomUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
@RequestMapping("/index")
public class AliPayController {


    /*@Autowired
    private FlowService flowService;*/


    @ResponseBody
    @RequestMapping("/Pay")
    public String Pay(String dingdan,String jinge) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl,AlipayConfig.app_id,AlipayConfig.merchant_private_key
        ,AlipayConfig.FORMAT,AlipayConfig.charset,AlipayConfig.alipay_public_key,AlipayConfig.sign_type);

        //创建请求
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();

        //封装传入参数
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(dingdan);//商品ID
        model.setSubject("图片");//商品名称
        model.setTotalAmount(jinge);//支付金额
       /* model.setBody(miaoshu);//商品描述*/
        model.setTimeoutExpress("2m");//超时时间
        model.setProductCode(RandomUtil.createRandNum());//商品Code


        request.setBizModel(model);
        request.setNotifyUrl(AlipayConfig.notify_url);//异步地址
        request.setReturnUrl(AlipayConfig.return_url);//同步回调地址

        //生成表单
        String from = alipayClient.pageExecute(request).getBody();
        System.out.println(from);
        return from;
    }

    @RequestMapping("/alipayReturnNotice")
    public ModelAndView alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) throws UnsupportedEncodingException, AlipayApiException {
        ModelAndView mv = new ModelAndView();
        System.out.println("支付成功后，支付宝返回的所有的数据："+ request);
        Map<String,String> map =  new HashMap();
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            System.out.println("return notice name:"+name);
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("params:"+params);
        boolean signVerified = AlipaySignature.rsaCheckV2(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        System.out.println("return notice signVerified:"+signVerified);
        mv.setViewName("pay/ok");
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            System.out.println("return out_trade_no:"+out_trade_no);
            System.out.println("return trade_no:"+trade_no);
            System.out.println("return total_amount:"+total_amount);
            //	System.out.println("return productName:"+ product.getName());



           /* // 修改订单状态，改为 支付成功，已付款; 同时新增支付流水
            orderService.updateOrderStatus(out_trade_no, trade_no, total_amount);*/

          /*  Orders order = orderService.getOrderById(out_trade_no);
            Product product = productService.getProductById(order.getProductId());*/
            mv.addObject("out_trade_no", out_trade_no);
            mv.addObject("trade_no", trade_no);
            mv.addObject("total_amount", total_amount);
        /*FlowChart flowChart = new FlowChart();
        flowChart.setCouId("1");
        flowChart.setCustId(313);
        flowChart.setFlowId(RandomNum.getRandomNickname(16));
        flowChart.setFlowMoney(Float.valueOf(total_amount));
        flowChart.setOrderId(out_trade_no);
        flowChart.setPaymentTime(new Date());
        flowChart.setStatus(1);
        boolean save = flowService.save(flowChart);
        System.out.println("流水数据生成状态:"+save);*/
        /*mv.addObject("productName", product.getName());*/

        return mv;
    }


}
